<template>
  <div>
    <el-cascader
      v-model="city"
      :options="options"
      :placeholder="placeholder"
      :props="cityProps"
      :disabled="disabled"
      clearable
      style="width: 100%"
    />
  </div>
</template>
<script>
import cityChina from './city-china.json'
import { cloneDeep } from 'lodash-es'

export default {
  name: 'CitySelector',
  // model: {
  //   prop: "value",
  //   event: "changeValue",
  // },
  props: {
    disabled: {
      type: Boolean,
      default: false
    },
    modelValue: {
      type: String,
      default: ''
    },
    level: {
      type: Number,
      default: 0
    },
    placeholder: {
      type: String,
      default: ''
    }
  },
  data() {
    return {
      city: ''
    }
  },
  computed: {
    cityProps() {
      return {
        expandTrigger: 'hover',
        emitPath: false
      }
    },
    options() {
      return this.jsonFormatTree(cityChina)
    }
  },
  watch: {
    modelValue: {
      handler(newVal) {
        this.city = newVal
      },
      immediate: true
    },
    city(newVal, oldVal) {
      this.$emit('update:modelValue', newVal)
    }
  },
  methods: {
    /**
     * @description: JS实现 JSON扁平数据转换树状数据
     * @param {*} jsonData
     * @return {*}
     */
    jsonFormatTree(jsonData) {
      const myData = cloneDeep(jsonData)
      const result = [],
        temp = {}
      let i = 0,
        j = 0,
        len = myData.length
      for (; i < len; i++) {
        temp[myData[i]['value']] = myData[i] // 以id作为索引存储元素，可以无需遍历直接定位元素
      }
      for (; j < len; j++) {
        const currentElement = myData[j]
        const tempCurrentElementParent = temp[currentElement['parent_code']] // 临时变量里面的当前元素的父元素 parentId 父级ID
        if (tempCurrentElementParent) {
          // 如果存在父元素
          if (!tempCurrentElementParent['children']) {
            // 如果父元素没有chindren键
            tempCurrentElementParent['children'] = [] // 设上父元素的children键
          }
          tempCurrentElementParent['children'].push(currentElement) // 给父元素加上当前元素作为子元素
        } else {
          // 不存在父元素，意味着当前元素是一级元素
          result.push(currentElement)
        }
      }
      return result
    }
  }
}
</script>
